﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Timers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Xml;
using EpiNEXT.Core;

namespace EpiNEXT.WPF.View.Pages
{
    /// <summary>
    /// A class designed to be the view model for a HOME page.
    /// </summary>
    public class HomeViewModel : ObservableObject
    {
        #region Members
        public ObservableCollection<ProjectInfo> _projectsInfo = new ObservableCollection<ProjectInfo>();
        private object _lock = new object();
        #endregion // Members

        #region Properties
        private Timer UpdateTimer { get; set; }

        public ObservableCollection<ProjectInfo> ProjectsInfo
        {
            get
            {
                return this._projectsInfo;
            }
            private set
            {
                if (this._projectsInfo != value)
                {
                    this._projectsInfo = value;
                    RaisePropertyChanged("ProjectsInfo");
                }
            }
        }
        #endregion // Properties

        #region Constructors
        /// <summary>
        /// Constructor
        /// </summary>
        public HomeViewModel()
        {
            ProjectsInfo = new ObservableCollection<ProjectInfo>();
            System.Windows.Data.BindingOperations.EnableCollectionSynchronization(ProjectsInfo, _lock);

            PopulateProjectList();

            this.UpdateTimer = new Timer(1000);
            this.UpdateTimer.Elapsed += UpdateTimer_Elapsed;
            this.UpdateTimer.Start();
        }
        #endregion // Constructors

        #region Methods

        private void UpdateTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            PopulateProjectList();
        }

        /// <summary>
        /// Populates the list of projects
        /// </summary>
        private void PopulateProjectList()
        {
            //string[] filePaths = Directory.GetFiles(@"C:\Users\bioha_000\Documents\Visual Studio 2013\Projects\EpiNEXT\EpiNEXT.WPF.View\bin\Debug\Projects\", "*.prj");
            string[] filePaths = Directory.GetFiles(@"C:\Users\EIAdmin\Source\Workspaces\epinext\EpiNEXT\EpiNEXT.WPF.View\bin\Debug\Projects", "*.prj");
            //string[] filePaths = Directory.GetFiles(@"C:\Users\knu1\Source\Workspaces\epinext\EpiNEXT\EpiNEXT.WPF.View\bin\Debug\Projects", "*.prj");
            
            if (filePaths.Length > 0)
            {
                foreach (string filePath in filePaths)
                {
                    bool fileFound = false;
                    foreach (ProjectInfo info in this.ProjectsInfo)
                    {
                        if (info.FileInfo.FullName.Equals(filePath, StringComparison.OrdinalIgnoreCase))
                        {
                            fileFound = true;
                            break;
                        }
                    }

                    if (fileFound) continue;

                    try
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(filePath);

                        XmlNode description = xmlDoc.SelectSingleNode("/Project/Description");
                        XmlNode summary = xmlDoc.SelectSingleNode("/Project/Summary");
                        XmlNode author = xmlDoc.SelectSingleNode("/Project/Author");
                        XmlNode created = xmlDoc.SelectSingleNode("/Project/Created");
                        XmlNode lastSaved = xmlDoc.SelectSingleNode("/Project/LastSaved");
                        XmlNode title = xmlDoc.SelectSingleNode("/Project/Title");
                        XmlNode id = xmlDoc.SelectSingleNode("/Project/Id");

                        if (lastSaved == null || created == null) continue;

                        XmlNode project = xmlDoc.SelectSingleNode("/Project");
                        ProjectInfo projectInfo = new ProjectInfo();
                        projectInfo.Title = title.InnerText;
                        projectInfo.Description = description.InnerText;
                        projectInfo.Summary = summary.InnerText;
                        projectInfo.Author = author.InnerText;

                        long saved;
                        bool success = long.TryParse(lastSaved.InnerText, out saved);
                        if (success)
                        {
                            projectInfo.LastSaved = new DateTime(saved);
                        }

                        projectInfo.FileInfo = new FileInfo(filePath);

                        // load forms
                        XmlNodeList nodes = xmlDoc.SelectNodes(@"/Project/Forms/Form");

                        foreach (XmlNode node in nodes)
                        {
                            FormInfo formInfo = new FormInfo();

                            XmlNode isChildNode = node.SelectSingleNode("IsRelatedForm");
                            XmlNode formIdNode = node.SelectSingleNode("Id");
                            XmlNode formTitleNode = node.SelectSingleNode("Title");

                            Guid formId = new Guid(formIdNode.InnerText);
                            string formTitle = formTitleNode.InnerText;
                            bool isRelatedForm = false;

                            if (isChildNode != null && isChildNode.InnerText != null && !String.IsNullOrEmpty(isChildNode.InnerText))
                            {
                                bool.TryParse(isChildNode.InnerText, out isRelatedForm);
                            }

                            if (isRelatedForm) continue;

                            formInfo.Title = formTitle;
                            formInfo.Id = formId;

                            XmlNode formLastSaved = node.SelectSingleNode("LastSaved");
                            XmlNode formDescription = node.SelectSingleNode("Description");

                            success = long.TryParse(formLastSaved.InnerText, out saved);
                            if (success)
                            {
                                formInfo.LastSaved = new DateTime(saved);
                            }

                            formInfo.Description = formDescription.Value;
                            formInfo.ProjectInfo = projectInfo;

                            projectInfo.Forms.Add(formInfo);
                        }

                        bool found = false;
                        foreach (ProjectInfo info in ProjectsInfo)
                        {
                            if (info.FileInfo.FullName.Equals(projectInfo.FileInfo.FullName, StringComparison.OrdinalIgnoreCase))
                            {
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            ProjectsInfo.Add(projectInfo);
                        }
                    }
                    catch (NullReferenceException)
                    {
                        continue;
                    }
                    catch(IOException)
                    {
                        continue;
                    }
                }
            }
        }
        #endregion // Methods
    }
}
